package com.icim.cxbh.export.controller;

import java.io.IOException;
import java.io.PrintWriter;

import javax.annotation.Resource;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.log4j.Logger;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

import com.icim.cxbh.export.parser.XmlParser;
import com.icim.cxbh.export.pojo.OqcInfo;
import com.icim.cxbh.export.service.DataImportService;

//@Controller
//@RequestMapping("/cxbh")
public class DataImportController {

    @Resource
    private DataImportService dataImportService;
    private Logger logger = Logger.getLogger(DataImportController.class);

//    @RequestMapping("/export.do")
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        req.setCharacterEncoding("UTF-8");
        resp.setCharacterEncoding("UTF-8");
        resp.setContentType("text/plain");

        String xml = req.getParameter("xml");
        logger.info(xml);

        PrintWriter out = resp.getWriter();
        if (xml == null) {
            out.println("No parameter xml");
        } else {
            String message;
            try {
                OqcInfo oqcInfo = XmlParser.parse(xml);
                dataImportService.importData(oqcInfo);
                message = "<transaction><rtn_code>0000000</rtn_code><rtn_mesg>SUCCESS</rtn_mesg></transaction>";
                out.println(message);

            } catch (Exception e) {
                message = "<transaction><rtn_code>9999999</rtn_code><rtn_mesg>";
                message += e.toString() + "</rtn_mesg></transaction>";
                out.println(message);
                throw new ServletException(e.getMessage());
            }
        }
        out.flush();
        out.close();
    }

    public static String getXml(int i) {
        StringBuffer buffer = new StringBuffer("<transaction><pallet_id></pallet_id><box_cnt>1</box_cnt>");
        buffer.append("<iary><model_id>C7550G450</model_id><work_qty>10000</work_qty><stkin_date>2035-04-23 11:22:00</stkin_date>");
        buffer.append("<box_id>").append("TZHTESTBOX").append(i).append("</box_id>");
        for (int j = 0; j < 10000; j++) {
            buffer.append("<iaryA><ea_id>").append("TESTEA");
            buffer.append(i).append(j).append("</ea_id></iaryA>");
        }
        buffer.append("</iary>");
        buffer.append("</transaction>");
        return buffer.toString();
    }

}
